package controller.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import controller.Playlist;
import controller.Track;



public class XSPFHandler extends DefaultHandler {
	
	private boolean inTrackListTag = false;
	private boolean inTrackTag = false;
	
	private StringBuffer tagcontent = new StringBuffer();
	
	private Playlist playlist;
	private Track currentTrack;
	
	public XSPFHandler(Playlist playlist) {
		this.playlist = playlist;
	}
	
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		
		tagcontent.setLength(0);
		
		if ("trackList".equals(qName)) {
			inTrackListTag = true;
		} else if ("track".equals(qName)) {
			inTrackTag = true;
			currentTrack = new Track();
		}
	}
	
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if ("trackList".equals(qName)) {
			
			inTrackListTag = false;
			
		} else if ("track".equals(qName)) {
			
			inTrackTag = false;
			playlist.add(currentTrack);
			
		} else if (inTrackTag) {
			String content = tagcontent.toString().trim();
			
			if ("location".equals(qName)) {
				currentTrack.setLocation(content);
			} else if ("album".equals(qName)) {
				currentTrack.setAlbum(content);
			} else if ("title".equals(qName)) {
				currentTrack.setTitle(content);
			} else if ("id".equals(qName)) {
				currentTrack.setId(Long.valueOf(content));
			}
		}
	}
	
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (inTrackListTag || inTrackTag) {
            tagcontent.append(ch,start,length);
        }
	}
	
}
